package com.ytjj.qmyx.data.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.request.AlipayMerchantOrderSyncRequest;
import com.alipay.api.response.AlipayMerchantOrderSyncResponse;
import com.github.pagehelper.PageHelper;
import com.ytjj.common.constants.AlipayConstants;
import com.ytjj.common.constants.DateUtils;
import com.ytjj.common.constants.QueueConstants;
import com.ytjj.common.dto.mqdto.OrderExpressDto;
import com.ytjj.common.dto.mqdto.SmsDto;
import com.ytjj.common.model.request.AliPayOrderSyncRequest;
import com.ytjj.common.service.RedisService;
import com.ytjj.common.utils.DateTimeUtil;
import com.ytjj.common.utils.ExpressDicUtil;
import com.ytjj.common.utils.feishu.FeiShuUtil;
import com.ytjj.qmyx.data.mapper.OrdersDao;
import com.ytjj.qmyx.data.service.OrdersService;
import com.ytjj.qmyx.mall.client.MallClient;
import com.ytjj.qmyx.mall.mapper.OrdersInfoMapper;
import com.ytjj.qmyx.mall.mapper.OrdersMapper;
import com.ytjj.qmyx.mall.mapper.OrdersPayMapper;
import com.ytjj.qmyx.mall.mapper.ReturnGoodsMapper;
import com.ytjj.qmyx.mall.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class OrdersServiceImpl implements OrdersService {
    @Resource
    private OrdersDao ordersDao;
    @Resource
    private OrdersInfoMapper ordersInfoMapper;
    @Resource
    private OrdersMapper ordersMapper;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private RedisService redisService;
    @Resource
    private ReturnGoodsMapper returnGoodsMapper;
    @Resource
    private OrdersPayMapper ordersPayMapper;
    @Resource
    private MallClient mallClient;
    @Resource
    private AlipayConstants alipayConstants;

    @Override
    public Orders findOrderByOrderId(Integer orderId) {
        return ordersDao.findOrderByOrderId(orderId);
    }

    @Override
    public List<OrdersInfo> queryOrdersList(String dayStr,Integer pageNo,Integer pageSize) {
        PageHelper.startPage(pageNo, pageSize);
        return ordersDao.queryOrdersList(dayStr);
    }

    @Override
    public Orders findOrderByChildOrderNo(String childOrderNo) {
        OrdersInfo ordersInfo = queryByChildOrderNo(childOrderNo);
        return ordersDao.findOrderByOrderId(ordersInfo.getOrderId());
    }

    @Override
    public void syncOrderExpress(OrderExpressDto dto) {
        if (dto.getUpdateOrderFlag().equals(1) && !StringUtils.isEmpty(dto.getChildOrderNo())) {
            ordersDao.updateExpressByChildOrderNo(dto.getChildOrderNo(), dto.getExpressCode(), dto.getExpressNo());
        } else if (dto.getUpdateOrderFlag().equals(0) && !StringUtils.isEmpty(dto.getChildOrderNo())) {
            OrdersInfo ordersInfo = queryByChildOrderNo(dto.getChildOrderNo());
            Orders orders = ordersMapper.selectByPrimaryKey(ordersInfo.getOrderId());
            if ("6".equals(orders.getOrderStatus())) {
                ReturnGoodsExample returnGoodsExample = new ReturnGoodsExample();
                returnGoodsExample.createCriteria().andOrdersInfoIdEqualTo(ordersInfo.getId());
                returnGoodsExample.setOrderByClause("id desc");
                List<ReturnGoods> list = returnGoodsMapper.selectByExample(returnGoodsExample);
                if (!CollectionUtils.isEmpty(list) && list.get(0).getStatus().equals(1)) {
                    FeiShuUtil.sendYxMsg(String.format("警告:子订单号为%s的售后订单准备发货!", dto.getChildOrderNo()));
                }
            }
            String orderinfoStatus = ordersInfo.getOrderinfoStatus();
            if (null != dto.getOrderInfoStatus() && !String.valueOf(dto.getOrderInfoStatus()).equals(ordersInfo.getOrderinfoStatus())) {
                ordersInfo.setOrderinfoStatus(dto.getOrderInfoStatus().toString());
            }
            if (org.apache.commons.lang.StringUtils.isNotBlank(dto.getExpressNo()) && !dto.getExpressNo().equals(ordersInfo.getExpressNo())) {
                ordersInfo.setExpressNo(dto.getExpressNo());
                ordersInfo.setDeliveryTime(dto.getImportTime());
            }
            if (org.apache.commons.lang.StringUtils.isNotBlank(dto.getExpressCode()) && !dto.getExpressCode().equals(ordersInfo.getExpressCompanyNo())) {
                ordersInfo.setExpressCompanyNo(dto.getExpressCode());
            }

            ordersInfoMapper.updateByPrimaryKeySelective(ordersInfo);
            //修改主订单状态
            List<OrdersInfo> ordersInfos = ordersInfoMapper.getAllOrdersInfoByOrderId(ordersInfo.getOrderId());
            if (!CollectionUtils.isEmpty(ordersInfos)) {
                int index = 0;
                for (OrdersInfo info : ordersInfos) {
                    if (info.getOrderinfoStatus().equals(ordersInfo.getOrderinfoStatus())) {
                        index += 1;
                    }
                }
                if (index == ordersInfos.size()) {
                    Orders order = new Orders();
                    order.setOrderStatus(ordersInfo.getOrderinfoStatus());
                    OrdersExample ordersExample = new OrdersExample();
                    ordersExample.createCriteria()
                            .andIdEqualTo(ordersInfo.getOrderId());
                    ordersMapper.updateByExampleSelective(order, ordersExample);
                }
            }
            log.info("订单之前状态orderinfoStatus:{},订单号:{}", orderinfoStatus,dto.getChildOrderNo());
            if ("1".equals(orderinfoStatus) && dto.getOrderInfoStatus() == 2) {
                sendDeliverySms(orders, ordersInfo, ordersInfos.size(),dto.getImportTime(),dto.getExpressNo(),dto.getExpressName());
            }

            //同步支付宝支付消息
            try{
                OrdersPay ordersPay = ordersPayMapper.queryByOrderNo(orders.getOrderNo());
                if (!StringUtils.isEmpty(ordersPay.getTradeType()) && "aliPay-jsApi".equals(ordersPay.getTradeType())) {
                    AliPayOrderSyncRequest request = new AliPayOrderSyncRequest();
                    request.setCreateTime(orders.getCreateTime());
                    request.setOrderId(orders.getId().toString());
                    request.setOrderStatus("IN_DELIVERY");
                    request.setUserId(orders.getUserId());
                    request.setChildId(ordersPay.getChildId());
                    request.setProductName(ordersInfo.getProductName());
                    request.setProductImg(ordersInfo.getProductImg());
                    request.setOrderNo(orders.getOrderNo());
                    mallClient.syncAliPayOrder(request);
                }
            }catch (Exception e) {

            }

        }
    }

    private OrdersInfo queryByChildOrderNo(String childOrderNo) {
        OrdersInfoExample ordersInfoExample = new OrdersInfoExample();
        ordersInfoExample.createCriteria().andChildOrderNoEqualTo(childOrderNo);
        List<OrdersInfo> ordersInfos = ordersInfoMapper.selectByExample(ordersInfoExample);
        if (CollectionUtils.isEmpty(ordersInfos)) {
            return null;
        }
        return ordersInfos.get(0);
    }
    private void sendDeliverySms(Orders orders, OrdersInfo ordersInfo, int size, Date importTime,String expressNo,String expressName) {
        log.info("开始发送发货短信 手机号:{},发货时间:{},token:{}",orders.getUserPhone(),importTime,orders.getH5Token());
//        String time =  DateTimeUtil.DateToStr(importTime);
//        String deliverySmsKey = "order:express:deliverySms"+orders.getUserPhone()+time;
//        String sendFlag = redisService.get(deliverySmsKey);
//        if(!StringUtils.isEmpty(sendFlag)) {
//            return;
//        }
        // 发送短信
        try {
            String productName = ordersInfo.getProductName();
            if (size > 1) {
                if (productName.length() > 12) {
                    productName = productName.substring(0, 12) + "-";
                } else {
                    productName = productName + "-";
                }
            } else {
                if (productName.length() > 12) {
                    productName = productName.substring(0, 12) + "-";
                }
            }
            SmsDto smsDto = new SmsDto();
            smsDto.setPhone(orders.getUserPhone());
            smsDto.setType(6);
            smsDto.setCode(productName);
            smsDto.setOrderSource(orders.getOrderSource());
            smsDto.setChannel(orders.getChannel());
            smsDto.setDomainUrl(orders.getDomainUrl());
            smsDto.setToken(orders.getH5Token());
            smsDto.setExpressNo(expressNo);
            smsDto.setExpressName(expressName);
            rabbitTemplate.convertAndSend(QueueConstants.SMS_QUEUE, smsDto);
//            redisService.set(deliverySmsKey,"1");
//            redisService.expire(deliverySmsKey,DateTimeUtil.getLastSeconds());
        } catch (Exception e) {
            log.error("供应链发货触发更新订单快递定点杆信息发送短信失败,{}",e);
        }
    }
}
